/*
@desc:银行卡申请提现
@author:binlety
*/

import React, { useState, useEffect, useMemo, useRef } from 'react';
import { Form, Card, Space, Radio, Input, Cascader, Button, Row, Col, Alert, Modal, message } from 'antd';
import CommonLoading from '@/components/CommonLoading';
import IconFont from '@/components/IconFont';
import SignModal from './SignModal';
import { useNavigate } from 'react-router-dom';
import { formatAmount, customTrimFunc } from '@/utils/utils.jsx';
import { getCurrentUser } from '@/utils/authority';
import { getAllArea } from '@/services/common';
import { getMoblieCaptchaOp, secondAccountSendsmsOp } from '../service';
import { isEmpty } from 'lodash';
import styles from '../index.module.less';

const reg = /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/ //提现金额正则
export default ({ obj, balanceObj, applyCashByBank, applyCashAliPay, virtualAccountApplyCash, secondAccountApplyCash }) => {

  const { id, type, bindFlag, bankType, openBankName, bankNo, name, mobile, cashAvailBal, surplusDiscount, companyGtFiftyThousandYuan, companyLtFiftyThousandYuan, secondCashAvailBal, virtualCashAvailBal } = obj

  const [form] = Form.useForm();
  const [countDown, setCount] = useState(0);//倒计时
  const [serviceFee, setFee] = useState(formatAmount(0)) //提现手续费
  const [finallyAmount, setAmount] = useState(formatAmount(0)) //提现到账金额
  const [loading, setLoading] = useState(false);
	const navigate = useNavigate();
  const [fromType, setFrom] = useState('oldPA');// oldPA: 老平安 newPA: 新平安  virtual: 虚拟账户
  const [cashType, setCashType] = useState('alipay');// alipay：支付宝  bank: 银行卡

  const [areaData, setAreaData] = useState([]);

  const stageData = useRef({});

  const [payChannels, setPayChannels] = useState({
    // oldPA: 100, //老平安
    // newPA: 2000, //新平安
    // virtual: 2000000, //虚拟账户
  });

  useEffect(() => {
    if (!isEmpty(obj)) {
      const formatState = {};
      let hasFixed = false;
      if(obj.accountNo && parseFloat(cashAvailBal)){
        formatState.oldPA = cashAvailBal;
        if(bankNo){
          hasFixed = true;
          setFrom('oldPA');
        }
      }
      if(parseFloat(secondCashAvailBal)){
        if(!hasFixed){
          hasFixed = true;
          setFrom('newPA');
        }
        formatState.newPA = secondCashAvailBal;
      }
      if(parseFloat(virtualCashAvailBal)){
        if(!hasFixed){
          hasFixed = true;
          setFrom('virtual');
        }
        formatState.virtual = virtualCashAvailBal;
      }
      setPayChannels(formatState);
      setFee(formatAmount(0));
      setAmount(formatAmount(0));
      form.resetFields();
    }
  }, [obj])

  useEffect(()=> {
    if(countDown){
      handleCountDown();
    }
  }, [countDown])

  const handleCountDown = () => {
    setTimeout(()=>{
      setCount(countDown - 1);
    }, 1000)
  }

  useEffect(() => {
    form.resetFields(['amount']);
    if(fromType == 'oldPA'){
      setFee(formatAmount(0));
      setAmount(formatAmount(0));
    }
  }, [fromType])

  useEffect(() => {
    if (cashType == 'bank' && !areaData.length) {
      getAreaList();
    }
    form.resetFields();
  }, [cashType])

  const canCashAmount = useMemo(() => {
    return payChannels[fromType];
  }, [fromType, payChannels])

  const minInput = useMemo(() => {
    if(fromType == 'oldPA'){
      return 6
    }
    return 0;
  }, [fromType])

  const renderFlag = useMemo(() => {
    const arr = Object.keys(payChannels);
    if (arr.length) {
      if(arr.length == 1 && fromType == 'oldPA' && !(bindFlag === 0) && !openBankName){//bindFlag	绑定标记 0:线下绑卡 1:线上绑卡 老数据可能为null
        return 1;
      }
      return 2;
    } 
  }, [payChannels])

  // 获取地区列表
  const getAreaList = async () => {
    setLoading(true);
    const { success, data = [] } = await getAllArea();
    if (success) {
      data.map(item => {
        item.childs.map(child => {
          child.childs = undefined;
        })
      })
      setAreaData(data);
    }
    setLoading(false);
  }

  //完全提现fill
  const allCach = () => {
    if (fromType != 'oldPA' || canCashAmount >= minInput) {
      form.setFieldsValue({ amount: canCashAmount });
      computeCode(Number(canCashAmount))
    } else {
      Modal.info({ content: `最小提现金额为${minInput}元` })
    }
  };

  //获取手机验证码(老平安)
  const getCaptcha = async () => {
    if(!fromType){
      return Modal.info({
        title:'温馨提示',
        content:'暂无可提现的账户'
      })
    }
    if (countDown) {
      return
    }else if(fromType == 'oldPA'){
      setLoading(true)
      const res = await getMoblieCaptchaOp({mobile:obj.mobile || getCurrentUser()?.mobile, type: 6});
      if(res.success){
        message.success('验证码发送成功！');
        setCount(59); 
      }
      setLoading(false)
    }else{
      getCaptchaII();
    }
  };

  //获取手机验证码(二类户)
  const getCaptchaII = () => {
    form.validateFields(['amount']).then(async value => {
      setLoading(true);
      const { amount: cashAmount } = value
      const res = await secondAccountSendsmsOp({ cashAmount });
      if(res.success){
        stageData.current = res.data;
        message.success('验证码发送成功！');
        setCount(59); 
      }
      setLoading(false)
    })
  };

  const [visible, setVisible] = useState(false);

  const onCheckSigned = async () => {
    form.validateFields().then(() => {
      if(balanceObj.agreementNo === '0' && balanceObj.hasOpenAccount == 1){
        setVisible(true)
      }else{
        onFinish();
      }
    })
  }

  //提现
  const onFinish = () => {
    form.validateFields().then(async (val) => {
      if (fromType == 'oldPA') {
        const { telphoneValidCode, amount, payPassword } = val
        if(bindFlag == 0){
         const params = customTrimFunc({
          payPassword,
          telphoneValidCode,
          accountType: 1,//先默认
          accountNo: obj.accountNo,
          bankName: openBankName,
          cardName: name,
          cardNo: obj.bankNo,
          cashType: obj.bankType == 3 ? 0 : 1,//0：支付宝 1：银行卡 
          frozenAmount: val.amount,
          industrialBeltFlag: INDUSTRIAL_BELT_FLAG,
          mobile: obj.mobile || getCurrentUser()?.mobile,
         })
         applyCashAliPay(params);
        }else{
          const params = customTrimFunc({
            mobile,
            payPassword,
            telphoneValidCode,
            accountBankId: id,
            bankCardType: type,
            bankHolder: name,
            freeAmount: serviceFee,
            frozenAmount: amount,
            incomeAccountNo: bankNo,
            incomeBank: openBankName,
            industrialBeltFlag: INDUSTRIAL_BELT_FLAG
          })
          applyCashByBank(params)
        }
      } else if(fromType == 'virtual'){
        const { amount, cashType, openCardAddress } = val;
        const params = customTrimFunc({
          ...val,
          frozenAmount: amount,
          cashType: cashType == 'alipay' ? 0 : 1,
          openCardAddress: openCardAddress ? openCardAddress.join('') : undefined,
          amount: undefined,
          accountNo: obj.accountNo,
          industrialBeltFlag: INDUSTRIAL_BELT_FLAG
        });
        virtualAccountApplyCash(params);
      }else if(fromType == 'newPA'){
        const { otpOrderNo, payOrderSn } = stageData.current;
        const { telphoneValidCode: otpValue, amount: frozenAmount } = val;
        secondAccountApplyCash(customTrimFunc({
          otpOrderNo, 
          payOrderSn,
          otpValue,
          frozenAmount,
          accountNo: obj.accountNo2,
          industrialBeltFlag: INDUSTRIAL_BELT_FLAG
        }))
      }
    });
  };

  //计算手续费 可到账金额
  const computeServiceFee = (value) => {
    if (fromType != 'oldPA') return;//其余个人卡均不需要手续费
    form.validateFields(['amount']).then(val => {
      computeCode(Number(val.amount))
    }).catch(() => {
      setFee("***")
      setAmount("***")
    })
  }

  //计算
  const computeCode = (amount) => {
    let fee //毛fee
    if (type == 1) {//个人
      // if(amount <= 1000){
      //   fee = personLeThousandYuan
      // }else if(1000 < amount && amount <= 50000){
      //   fee = personLeFiftyThousandYuan
      // }else if(amount > 50000){
      //   fee = personGtFiftyThousandYuan
      // }
      fee = 0
    } else if (type == 2) {//企业
      if (amount <= 50000) {
        fee = companyLtFiftyThousandYuan
      } else if (amount > 50000) {
        fee = companyGtFiftyThousandYuan
      }
    }
    if (surplusDiscount && surplusDiscount >= fee) {
      setFee(formatAmount(0))
      setAmount(formatAmount(amount))
      return
    }
    setFee(formatAmount(fee))
    setAmount(formatAmount((amount * 1000 - fee * 1000) / 1000))
  }

  //去绑卡
  const redirectFunc = () => {
    navigate('/account/safety', {state: {bindCard: true}});
  }

  const signModalProps = {
    accountNo: obj.accountNo,
    handleOk(){
      balanceObj.agreementNo = '1';
      setVisible(false);
    },
    handleCancel(){
      setVisible(false);
    }
  }

  return (
    <>
      {!renderFlag && <span>正在加载中，如有问题可稍后刷新重试！</span>}
      {renderFlag == 1 && (<>
        <Alert
          style={{ marginBottom: '24px' }}
          message="仅支持已绑定银行卡的用户进行银行卡提现操作"
          type="info"
          showIcon
        />
        <Button type="primary" style={{ marginLeft: 24 }} onClick={redirectFunc}>
          去绑定
        </Button>
      </>)}
      {renderFlag == 2 && (
        <>
          <Row className={styles.spceRelativeBox}>
            <Col span={18} offset={4}>
              <Card size="small" title="1、选择提现账户" style={{ width: 412 }}>
                <Radio.Group style={{ marginTop: '8px' }} onChange={(e) => setFrom(e.target.value)} value={fromType}>
                  <Space direction="vertical">
                    {Object.keys(payChannels).map(item => {
                      if (item == 'oldPA') {
                        return <Radio key={item} value={item} disabled={!bankNo}>
                          见证宝：<span className={[openBankName ? "common-color9" : ''].join(' ')}>{formatAmount(payChannels[item])}元{!(bindFlag === 0) && !openBankName && '（未绑卡）'}</span></Radio>
                      } else if (item == 'newPA') {
                        return <Radio key={item} value={item}>二类户：<span className='common-color9'>{formatAmount(payChannels[item])}元</span></Radio>
                      } else if (item == 'virtual') {
                        return <Radio key={item} value={item}>虚拟账户：<span className='common-color9'>{formatAmount(payChannels[item])}元（线下打款）</span></Radio>
                      }
                    })}
                  </Space>
                </Radio.Group>
              </Card>
            </Col>
          </Row>

          {
            (fromType == 'newPA' || (fromType == 'oldPA' && (bindFlag == 1 || bankType != 3))) && (<>
              <Row className={styles.spceRelativeBox}>
                <Col span={18} offset={4}>
                  <Card size="small" title="2、到账银行卡" style={{ width: 412 }}>
                    <Space direction="vertical">
                      <p><span>开户银行</span>：{fromType == 'newPA' ? obj?.openBankName2 : openBankName}</p>
                      <p><span>银行卡号</span>：{fromType == 'newPA' ? obj?.bankNo2 : bankNo}</p>
                      <p><span>开户人姓名</span>：{fromType == 'newPA' ? obj?.name2 : name}</p>
                      <p style={{marginBottom:0}}><span>手机号</span>：{fromType == 'newPA' ? obj?.mobile2 : mobile}</p>
                    </Space>
                  </Card>
                </Col>
                <Col span={18} offset={4}>
                  <p style={{ width: 412, marginTop: 4 }}>注：{type == 2 ? `企业银行卡提现金额小于等于50000手续费${companyLtFiftyThousandYuan}元/笔，提现金额大于50000手续费${companyGtFiftyThousandYuan}元/笔` : '个人类型的银行卡暂无提现手续费'}</p>
                </Col>
              </Row>
            </>
            )
          }

          {
            (fromType == 'oldPA' && !bindFlag && bankType == 3) && (<Row className={styles.spceRelativeBox}>
               <Col span={18} offset={4}>
                  <Card size="small" title="2、到账支付宝" style={{ width: 412 }}>
                    <Space direction="vertical">
                      <p><span>支付宝账号</span>：{bankNo}</p>
                      <p style={{marginBottom:0}}><span>支付宝姓名</span>：{name}</p>
                    </Space>
                  </Card>
                </Col>
            </Row>
            )
          }

          <Form
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            layout="horizontal"
            form={form}
            initialValues={{ openBankName, bankNo, name, mobile, cashType: cashType }}
            onFinish={onCheckSigned}
            scrollToFirstError
          >
            {/* 提现金额 */}
            <Form.Item
              label={<span className="lable-require">提现金额</span>}
              style={{ marginBottom: 0, height: 'auto' }}
            >
              <Row gutter={8}>
                <Col style={{ width: 248 }}>
                  <Form.Item
                    name="amount"
                    rules={[
                      ({ }) => ({
                        validator(rule, amount) {
                          const value = amount ? amount?.trim() : '0'
                          if (!reg.test(value) || value - 0 <= 0) {
                            return Promise.reject('请正确输入金额，不能超过两位小数');
                          }
                          if (canCashAmount - 0 < value - 0) {
                            return Promise.reject('提现金额必须小于可用金额');
                          }
                          if (fromType == 'oldPA' && value - 0 < minInput) {
                            return Promise.reject(`最小提现金额为${minInput}元`);
                          }
                          return Promise.resolve();
                        },
                      })
                    ]}
                    extra={
                      <div>
                        <span style={{ display: "inline-block" }}>可用余额：</span>
                        <span className='common-color9'>{(canCashAmount || canCashAmount == 0) ? canCashAmount : '***'}</span> 元
                      </div>
                    }
                  >
                    <Input suffix="元" autoComplete="off" onChange={(e) => computeServiceFee(e.target.value.trim())} className={styles.inputAliRig} />
                  </Form.Item>
                </Col>
                <Col style={{ width: 90 }}>
                  <Button type="link" onClick={allCach} style={{ padding: 0 }}>
                    全部提现
                  </Button>
                </Col>
              </Row>
            </Form.Item>

            {fromType != 'virtual' && (
              <>
                {/* 手机验证码 */}
                <Form.Item label={<span className="lable-require">手机验证码</span>}>
                  <Row gutter={8}>
                    <Col>
                      <Form.Item
                        name="telphoneValidCode"
                        noStyle
                        rules={[{ required: true, message: '请输入手机验证码！' }]}
                      >
                        <Input style={{ width: 240 }} autoComplete="off" />
                      </Form.Item>
                    </Col>
                    <Col>
                      <Button onClick={getCaptcha}>
                        {countDown? `${countDown}s` : '获取验证码'}
                      </Button>
                    </Col>
                  </Row>
                </Form.Item>
                {
                  fromType == 'oldPA' && (
                    <>
                     {/* 支付密码 */}
                    <Form.Item
                      name="payPassword"
                      label="支付密码"
                      rules={[{ required: true, message: '请输入支付密码！' }]}
                    >
                      <Input.Password style={{ width: 240 }} autoComplete="new-password" />
                    </Form.Item>
                    {
                      (type == 2 && !!parseFloat(serviceFee)) && (
                        <Row className={styles.spceRelativeBox}>
                        <Col span={18} offset={4}>
                          <Card size="small" style={{ width: 412 }}>
                            <Space direction="vertical">
                              <p><span>提现手续费</span>：{serviceFee}元</p>
                              <p><span>提现到账金额</span>：{finallyAmount}元</p>
                              <p><span>手续费剩余补助</span>：<span className='common-color9'>{formatAmount(Number(surplusDiscount))}</span>元</p>
                              <div>
                                <IconFont type='iconjingshi' style={{ marginRight: '5px' }} />
                                <span className='common-color13'>该笔提现手续费将由{APP_TITLE}平台补助给客户</span><br />
                                <span className='common-color8' style={{ fontSize: '12px', textIndent: '24px', display: 'inline-block' }}>(如果补助额度不足手续费由自己承担)</span>
                              </div>
                            </Space>
                          </Card>
                        </Col>
                      </Row>
                      )
                    }
                    </>
                  )
                }
              </>
            )}

            {fromType == 'virtual' && (
              <Form.Item name='cashType' label="选择提现方式" rules={[{ required: true }]}>
                <Radio.Group onChange={(e) => setCashType(e.target.value)} value={cashType}>
                  <Radio value={'alipay'}>提现到支付宝</Radio>
                  <Radio value={'bank'}>提现到银行卡</Radio>
                </Radio.Group>
              </Form.Item>
            )}

            {(fromType == 'virtual' && cashType == 'alipay') && (
              <>
                <Form.Item name="cardNo" label="支付宝账号" rules={[{ required: true }, { pattern: /^[^\u4e00-\u9fa5]+$/, message: '请输入正确的支付宝账号' }]}>
                  <Input style={{ width: 240 }} autoComplete="off" placeholder='请输入提现支付宝账号' maxLength={50} />
                </Form.Item>
                <Form.Item name="cardName" label="支付宝真实姓名" rules={[{ required: true }, { pattern: /^[^0-9]+$/, message: '请输入正确的支付宝真实姓名' }]}>
                  <Input style={{ width: 240 }} autoComplete="off" placeholder='请输入支付宝真实姓名' maxLength={50} />
                </Form.Item>
              </>
            )}

            {(fromType == 'virtual' && cashType == 'bank') && (
              <>
                <Form.Item name="bankName" label="开户银行" rules={[{ required: true }, { pattern: /[\u4e00-\u9fa5]/, message: '请输入正确的开户银行' }]}>
                  <Input style={{ width: 240 }} autoComplete="off" placeholder='请输入开户银行，如：招商银行' maxLength={50} />
                </Form.Item>
                <Form.Item name="subBankName" label="支行名称/联行号" rules={[{ required: true }, { pattern: /[\u4e00-\u9fa5]/, message: '请输入正确的支行名称/联行号' }]}>
                  <Input style={{ width: 240 }} autoComplete="off" placeholder='请输入支行名称，如：南通支行' maxLength={50} />
                </Form.Item>
                <Form.Item name="openCardAddress" label="开户地" rules={[{ required: true, message: '请选择开户地' }]}>
                  <Cascader style={{ width: 240 }} options={areaData} fieldNames={{ label: 'name', value: 'name', children: 'childs' }} placeholder="请选择地区" />
                </Form.Item>
                <Form.Item name="cardNo" label="银行卡号" rules={[{ required: true }, { pattern: /^[1-9]\d*$/, message: '请输入正确的银行卡号' }]}>
                  <Input style={{ width: 240 }} autoComplete="off" placeholder='请输入银行卡号' maxLength={25} />
                </Form.Item>
                <Form.Item name="cardName" label="开户人姓名" rules={[{ required: true }, { pattern: /^[^0-9]+$/, message: '请输入正确的开户人姓名' }]}>
                  <Input style={{ width: 240 }} autoComplete="off" placeholder='请输入开户人姓名' maxLength={50} />
                </Form.Item>
              </>
            )}

            <Form.Item label=" " colon={false}>
              {fromType == 'virtual' && <p className='common-color13' style={{ padding: '0 0 6px 0', fontSize: '12px' }}>注：请仔细填写提现相关信息，避免因填写错误，导致未收到提现金额</p>}
              <Button type="primary" htmlType="submit">
                确认提交
              </Button>
            </Form.Item>
          </Form>
        </>
      )}
      { visible && <SignModal {...signModalProps} />}
      <CommonLoading loading={loading} />
    </>
  );
};
